import { Watcher } from '../watcher.js'

const CompileUtil = {

  setVal(vm, expr, value) {
    const exprArr = expr.split('.')

    exprArr.reduce((data, current, curIndex) => {
      if(curIndex === exprArr.length - 1) {
        data[current] = value 
      }
      return data[current]
    }, vm.$data)
  },

  //根据 vm 和 表达式，从 vm 中获取数据
  getVal(vm, expr) {
    return expr.split('.').reduce((data, current) => {
      return data[current]
    }, vm.$data)
  },
  
  model(node, expr, vm) {
    new Watcher(vm, expr, newValue => {
      node.value = newValue
    })
    node.value = this.getVal(vm, expr)
    node.addEventListener('input', e =>{
      this.setVal(vm, expr, e.target.value)
    })
  },

  getContentValue(vm, expr) {
    return expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
      return this.getVal(vm, args[1])
    })
  },

  text(node, expr, vm) {
    let content =  expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
      new Watcher(vm, args[1], () => { //每次匹配到一个就创建一个Watcher对象
        node.textContent = this.getContentValue(vm, expr); 
      });
      return this.getVal(vm, args[1]);
    });
    node.textContent  = content; // 替换文本节点的内容
  }
}

export default CompileUtil